import React, {useMemo} from 'react';
import {CartesianGrid, Legend, Line, LineChart, ResponsiveContainer, Tooltip, XAxis, YAxis} from 'recharts';
import * as PensionCalc from '../utils/pensionCalculations.js';
import {createTooltipFormatter, formatCurrency, formatYears} from '../utils/chartUtils.jsx';

/**
 * 缴费年限-月养老金关系图
 * @param {Object} props - 组件属性
 * @param {number} props.currentSalary - 当前税前工资
 * @param {number} props.localAverageSalary - 当地上年度在岗职工月平均工资
 * @param {number} props.retirementAge - 退休年龄
 * @param {string} props.employmentType - 就业类型（在职/灵活）
 * @param {number} props.baseRate - 灵活就业基准比例
 * @returns {JSX.Element}
 */
const PensionByYearsChart = ({
                                 currentSalary,
                                 localAverageSalary,
                                 retirementAge,
                                 employmentType,
                                 baseRate
                             }) => {
    const data = useMemo(() => {
        const chartData = [];
        const payoutMonths = PensionCalc.getPayoutMonths(retirementAge);
        const minYears = 15; // 最低缴费年限为15年
        const maxYears = 40; // 设置最大缴费年限为40年

        for (let years = minYears; years <= maxYears; years++) {
            let personalIndexedSalary, personalAccountTotal, totalContribution;

            // 针对不同就业类型计算
            if (employmentType === 'employee') {
                // 在职人员
                const contributionIndex = PensionCalc.calculateContributionIndex(currentSalary, localAverageSalary);
                personalIndexedSalary = PensionCalc.calculatePersonalIndexedSalary(localAverageSalary, contributionIndex);

                // 限制计算缴费基数在60%-300%之间
                const limitedSalary = Math.max(localAverageSalary * 0.6, Math.min(localAverageSalary * 3, currentSalary));
                personalAccountTotal = PensionCalc.calculateEmployeePAT(limitedSalary, 0.08, years);
                totalContribution = PensionCalc.calculateEmployeeTotalContribution(limitedSalary, 0.08, years);
            } else {
                // 灵活就业人员
                personalIndexedSalary = PensionCalc.calculatePersonalIndexedSalary(localAverageSalary, baseRate);
                personalAccountTotal = PensionCalc.calculateFreelancerPAT(localAverageSalary, baseRate, years);
                totalContribution = PensionCalc.calculateFreelancerTotalContribution(localAverageSalary, baseRate, years);
            }

            // 计算养老金
            const basicPension = PensionCalc.calculateBasicPension(localAverageSalary, personalIndexedSalary, years);
            const personalAccountPension = PensionCalc.calculatePersonalAccountPension(personalAccountTotal, payoutMonths);
            const monthlyPension = PensionCalc.calculateMonthlyPension(basicPension, personalAccountPension);

            // 计算收支平衡点
            const breakEvenPoint = PensionCalc.findBreakEvenPoint(totalContribution, monthlyPension);

            chartData.push({
                years,
                monthlyPension,
                basicPension,
                personalAccountPension,
                totalContribution,
                breakEvenPoint
            });
        }

        return chartData;
    }, [currentSalary, localAverageSalary, retirementAge, employmentType, baseRate]);

    // 使用通用tooltip格式化器
    const CustomTooltip = createTooltipFormatter({
        formatLabel: (label) => `缴费年限: ${label}年`,
        formatters: {
            monthlyPension: (value) => formatCurrency(value),
            basicPension: (value) => formatCurrency(value),
            personalAccountPension: (value) => formatCurrency(value),
            totalContribution: (value) => formatCurrency(value, false),
            breakEvenPoint: (value) => formatYears(value)
        },
        nameMap: {
            monthlyPension: '月养老金',
            basicPension: '基础养老金',
            personalAccountPension: '个人账户养老金',
            totalContribution: '个人缴费总额',
            breakEvenPoint: '收支平衡点'
        }
    });

    return (
        <div className="chart-container">
            <h3>缴费年限-月基本养老金关系图</h3>
            <p className="chart-description">
                本图表展示不同缴费年限下的月基本养老金变化趋势。紫色线表示月基本养老金总额，绿色线表示基础养老金部分，
                黄色线表示个人账户养老金部分。您可以从图表看出延长缴费年限如何增加您的月养老金。
                缴费年限范围从法定最低的15年到最高的40年。
            </p>
            <ResponsiveContainer width="100%" height={400}>
                <LineChart
                    data={data}
                    margin={{
                        top: 20,
                        right: 30,
                        left: 20,
                        bottom: 10,
                    }}
                >
                    <CartesianGrid strokeDasharray="3 3"/>
                    <XAxis
                        dataKey="years"
                        label={{value: '缴费年限（年）', position: 'insideBottomRight', offset: -5}}
                    />
                    <YAxis
                        label={{value: '月基本养老金（元）', angle: -90, position: 'insideLeft'}}
                        tickFormatter={(value) => formatCurrency(value, false)}
                    />
                    <Tooltip content={<CustomTooltip/>}/>
                    <Legend/>
                    <Line
                        type="monotone"
                        dataKey="monthlyPension"
                        name="月基本养老金"
                        stroke="#8884d8"
                        activeDot={{r: 8}}
                    />
                    <Line
                        type="monotone"
                        dataKey="basicPension"
                        name="基础养老金"
                        stroke="#82ca9d"
                    />
                    <Line
                        type="monotone"
                        dataKey="personalAccountPension"
                        name="个人账户养老金"
                        stroke="#ffc658"
                    />
                </LineChart>
            </ResponsiveContainer>
        </div>
    );
};

export default PensionByYearsChart; 